package controllers;

import java.util.ArrayList;

import messages.InfoSystemsMsg;
import client.gui.panels.NewRequest;
import client.gui.panels.PanelIF;
import entities.GeneralInformationStage;
import entities.InfoSystem;
import entities.Message;
import entities.ObjectType;
import entities.Ticket;

public class NewRequestController implements ControllerIF {
	
	/**
	 * the new request panel
	 */
	private NewRequest newRequestPanel;
	
	/**
	 * the main panel controller
	 */
	private MainPanelController mainPanelController;
	
	/**
	 * A structure to hold all the information inserted 
	 */
	private Ticket ticket;
	
	/**
	 * Array of all the available information systems to open a ticket about
	 */
	private ArrayList<InfoSystem> informationSystem;
	
	
	public NewRequestController(MainPanelController mainPanelController) {
		this.mainPanelController = mainPanelController;
		this.mainPanelController.setInnerPanelController(this);
	}	

	/**
	 * receive any message from server
	 * @param message Message
	 */
	@Override
	public void decipherMessage(Message message) {
		if(message.getObjType().equals(ObjectType.INFO_SYSTEM)) {
			informationSystem = ((InfoSystemsMsg) message.getObject()).getInfoSystems();
			newRequestPanel = new NewRequest(informationSystem);
			newRequestPanel.setController(this);
			mainPanelController.setInnerPanel(newRequestPanel);
		}
	}
	
	@Override
	public void action() {
		String[] comments = ((NewRequest) newRequestPanel).getCommentsTextArea().split(" ");
		ticket = new Ticket();
		for(int i = 0; i < informationSystem.size(); i++) {
			if(((NewRequest) newRequestPanel).getSystemComboBox() == informationSystem.get(i).getS_name())
				ticket.setInfoSystem(new InfoSystem(informationSystem.get(i).getS_id(), informationSystem.get(i).getS_name()));
		}
		GeneralInformationStage generalInfo = new GeneralInformationStage();
		generalInfo.setExistingSituationDescription(((NewRequest) newRequestPanel).getExistingTextArea());
		generalInfo.setRequestedChangedDescription(((NewRequest) newRequestPanel).getRequestedTextArea());
		generalInfo.setReasonForRequest(((NewRequest) newRequestPanel).getReasonTextArea());
		if(!((NewRequest) newRequestPanel).getCommentsTextArea().isEmpty() || comments.length > 0)
			generalInfo.setComments(((NewRequest) newRequestPanel).getCommentsTextArea());
		else
			generalInfo.setComments(new String(""));
		ticket.setGeneralInfo(generalInfo);
		
		mainPanelController.storeTicket(ticket);
	}
	
	@Override
	public PanelIF getPanel() {
		return this.newRequestPanel;
	}

	@Override
	public void setPanel(PanelIF panel) {
		this.newRequestPanel = (NewRequest) panel;
	}

}
